package net.hualisheng.netty.service;

import net.hualisheng.netty.entity.UserRedpack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service("grabRedPackService")
@DependsOn(value = {"userRedEnvelopeServiceImpl","redEnvelopeServiceImpl"})
public class GrabRedPackServiceImpl implements GrabRedPackService {

    private static final Logger logger= LoggerFactory.getLogger(GrabRedPackServiceImpl.class);

    private static final int redPackId=1;

    private static final  String amount= "10.00";

    @Autowired
    private UserRedEnvelopeService userRedEnvelopeService;

    @Autowired
    private RedEnvelopeService redEnvelopeService;
    /**
     * 抢红包的业务处理
     *
     * @param userId
     */
    @Override
    public void gradRedPack(String userId) {
        // 1.查询剩余红包个数
        try {
            int count = redEnvelopeService.getRedEnvelopeCount(redPackId);

            if (count>0){
                //2. 扣减红包
                int i = redEnvelopeService.reduceRedEnvelope(redPackId);

                if (i>0){
                    //3. 抢红包作业成功
                    UserRedpack redPack = new UserRedpack();
                    redPack.setAmount(new BigDecimal(amount));
                    redPack.setUserid(userId);
                    redPack.setRedpackid(redPackId);
                    redPack.setGrabdate(new Date());
                    //4. 插入操作记录
                    userRedEnvelopeService.insertGradReadPack(redPack);
                }
            }
        } catch (Exception e) {
            logger.error("抢红包作业失败:"+e.getMessage());
            throw new RuntimeException("系统作业发生异常");
        } finally {
        }
    }
}
